package com.atguigu.client;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * className: ChatClient
 * description:客户端
 * date: 2023/3/10 0010-16:08
 * <p>
 * project: nio
 * package: com.atguigu.client
 * email: 1085844536@qq.com
 * version:
 *
 * @author WangGuojian
 */
public class ChatClient {

    /**
     * 启动客户端方法
     *
     * @param name {@link String}
     */
    public void startClient(String name) throws IOException {
        // 连接服务端
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8000));

        // 接收服务器端响应数据
        Selector selector = Selector.open();
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_READ);
        // 创建线程
        new Thread(new ClientThread(selector)).start();

        // 向服务器端发送消息
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String msg = scanner.nextLine();
            if (msg.length() > 0) {
                socketChannel.write(StandardCharsets.UTF_8.encode(name + ":" + msg));
            }
        }
    }

    /**
     * @param args {@link String}
     */
    public static void main(String[] args) {

    }
}
